import Layout from '@/layout'
import { createRouter, createWebHistory } from 'vue-router'

const routes = [
	{
		path: '/login',
		name: 'login',
		component: () => import('@/views/login'),
		meta: { title: '登录页', hidden: true },
	},
	{
		path: '',
		component: Layout,
		redirect: 'home',
		meta: { title: '首页', hidden: true },
		children: [
			{
				path: 'home',
				name: 'Home',
				component: () => import('@/views/home'),
				meta: { title: '首页' },
			},
		],
	},
	{
		path: '/echarts',
		component: Layout,
		redirect: '/echarts/echartsMap',
		meta: { title: 'echarts', icon: 'Folder' },
		//通过children配置子级路由
		children: [
			{
				path: 'echartsMap',
				name: 'echartsMap',
				component: () => import('../views/echarts/echartsMap'),
				meta: { title: 'echarts地图', icon: 'Files' },
			},
			{
				path: 'echartsItem',
				name: 'echartsItem',
				component: () => import('@/views/echarts/echartsItem'),
				meta: { title: 'echarts图表', icon: 'Files' },
			},
		],
	},
	{
		path: '/packageComponent',
		component: Layout,
		redirect: '/packageComponent/searchTablePage',
		meta: { title: '组件封装', icon: 'Folder' },
		children: [
			{
				path: 'searchTablePage',
				name: 'searchTablePage',
				component: () => import('../views/searchTablePage'),
				meta: { title: '表格查询', icon: 'List' },
			},
		],
	},
	{
		path: '/:catchAll(.*)',
		name: '404',
		meta: {
			title: '页面不存在',
			hidden: true,
		},
		component: () => import('@/views/errorpage/error404'),
	},
]

// console.log('[ routes ] >', routes)

const router = new createRouter({
	history: createWebHistory(),
	routes,
	// 切换路由后滚动条置顶
	scrollBehavior() {
		return {
			x: 0,
			y: 0,
		}
	},
})

// 添加路由导航守卫
// 用来对访问的路由进行权限控制
// 除了login这个路由其他的路由都要进行了登录之后才能访问
router.beforeEach((to, from, next) => {
	if (to.path === '/login' || window.sessionStorage.getItem('user'))
		return next()
	return next('/login')
})

export default router
